//公共方法
const constants = require('../../tools/constants');
const fs = require('fs');
const moment = require('moment');
const nthline = require('nthline');
const crypto = require('crypto')
//AvenirSQL
const AvenirKey = "7a6b3b4cd76a7e6c";
const AvenirIv = 'e104108cdf1b691e';
const nwcl = require('nwc-l');
const os = require('os');
const { initial } = require('lodash');

exports.getError = (type, strict) => {
    this.toLog("需要获取的error为 ", type);
    if (!constants.errCode[type]) {
        if (type === undefined) {
            type = 'UNKNOWN_ERROR';
        } else {
            throw {
                code: -44944,
                message: type
            }
        }
    }
    if (strict) {
        throw ({
            code: constants.errCode[type].code,
            message: constants.errCode[type].message
        })
    }

    return {
        code: constants.errCode[type].code,
        message: constants.errCode[type].message
    }
}

exports.fileExists = (fileName, strict) => {
    if (!fs.existsSync(fileName)) {
        strict ? this.getError('FILE_NOT_EXIST', true) : fs.writeFileSync(fileName, '');

    }
    return true;
}

//给用户一个签名
exports.getSign = (info) => {
    let nowTime = moment().valueOf();
    let rand = Math.random();
    let sign = info.address + rand.toString().slice(3) + nowTime.toString();
    return genSign(sign);
}

genSign = (src) => {
    let sign = '';
    let key = Buffer.from(AvenirKey, 'utf-8');
    let iv = Buffer.from(AvenirIv, 'utf-8')
    const cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
    sign += cipher.update(src, 'utf8', 'hex');
    sign += cipher.final('hex');
    return sign;
}

// 解密  
deSign = (sign, key = Buffer.from("7a6b3b4cd76a7e6c", 'utf-8'), iv = Buffer.from('e104108cdf1b691e', 'utf-8')) => {
    let src = '';
    const cipher = crypto.createDecipheriv('aes-128-cbc', key = Buffer.from("7a6b3b4cd76a7e6c", 'utf-8'), iv = Buffer.from('e104108cdf1b691e', 'utf-8'));
    src += cipher.update(sign, 'hex', 'utf8');
    src += cipher.final('utf8');
    return src;
}


//读文件的某一行 注意是从0开始的
exports.readIndex = async (index, fileName) => {
    try {
        return await nthline(index, fileName);
    } catch (error) {
        //报错是文件被读完了
        this.toLog('readIndex error->',error);
        return null;
    }
}


//统计一个文件有多少行
exports.countLine = (fileName) => {
    return nwcl.sync(fileName);
}

//去掉单双引号
exports.delQuotation = (value) => {
    value = value.toString().replace(/\"/g, "");
    value = value.toString().replace(/\'/g, "");
    return value;
}

//根据配置文件决定是否输出日志
exports.toLog = (...value) => {
    !ini.main.ifConsoleLog || console.log(value);
}

// //加锁的级别 按 select insert update delete 生成0-1组合
// exports.lockLevel = {
//     all : 15,       //1111 四种操作都不允许
//     noSelect:7,        //0111
//     noInsert:11,    //1011
//     noUpdate:13,       //1101
//     noDelete:14,        //1110
// }



exports.EOL = os.EOL;